// 全局变量
// 在文件顶部添加以下代码
// 浏览器兼容性处理
function setupMediaDevices() {
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }

    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
            const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            
            if (!getUserMedia) {
                return Promise.reject(new Error('您的浏览器不支持摄像头访问'));
            }

            return new Promise(function(resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    }
}

// 删除其他DOMContentLoaded事件，只保留一个
document.addEventListener('DOMContentLoaded', function() {
    // 设置媒体设备兼容性
    setupMediaDevices();
    
    // 初始化视频元素
    video = document.getElementById('video');
    
    // 初始化画布
    originalCanvas = document.getElementById('originalCanvas');
    originalCtx = originalCanvas.getContext('2d');
    
    resultCanvas = document.getElementById('resultCanvas');
    resultCtx = resultCanvas.getContext('2d');
    
    // 设置事件监听器
    document.getElementById('startButton').addEventListener('click', startCapture);
    document.getElementById('stopButton').addEventListener('click', stopCapture);
    
    // 添加下载按钮功能（如果HTML中有下载按钮）
    const downloadButton = document.getElementById('downloadButton');
    if (downloadButton) {
        downloadButton.addEventListener('click', downloadResult);
    }
    
    // 设置窗口大小变化时重新调整画布
    window.addEventListener('resize', setCanvasSize);
    setCanvasSize();
    
    console.log("DOM初始化完成");
});
let video;
let mediaStream;
let websocket;
let originalCanvas, originalCtx;
let resultCanvas, resultCtx;
let animationId;
let isProcessing = false;
let frameCount = 0;
let lastFpsUpdate = 0;

// DOM加载完成后执行初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化视频元素
    video = document.getElementById('video');
    
    // 初始化画布
    originalCanvas = document.getElementById('originalCanvas');
    originalCtx = originalCanvas.getContext('2d');
    
    resultCanvas = document.getElementById('resultCanvas');
    resultCtx = resultCanvas.getContext('2d');
    
    // 设置事件监听器
    document.getElementById('startButton').addEventListener('click', startCapture);
    document.getElementById('stopButton').addEventListener('click', stopCapture);
    
    // 设置窗口大小变化时重新调整画布
    window.addEventListener('resize', setCanvasSize);
    setCanvasSize();
});

// 设置画布尺寸
function setCanvasSize() {
    const containerWidth = document.querySelector('.canvas-stack').offsetWidth;
    const aspectRatio = 480 / 640;
    
    originalCanvas.width = containerWidth;
    originalCanvas.height = containerWidth * aspectRatio;
    
    resultCanvas.width = containerWidth;
    resultCanvas.height = containerWidth * aspectRatio;
}

// 开始视频捕捉
async function startCapture() {
    try {
        // 检查浏览器是否支持mediaDevices
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            throw new Error('浏览器不支持访问摄像头。请尝试使用Chrome/Firefox/Edge等现代浏览器。');
        }
        
        // 获取视频流
        mediaStream = await navigator.mediaDevices.getUserMedia({
            video: {
                width: { ideal: 640 },
                height: { ideal: 480 }
            }
        });
        
        // 设置视频源
        video = document.getElementById('video');
        if (!video) {
            throw new Error('找不到视频元素，请检查HTML');
        }
        video.srcObject = mediaStream;
        await video.play(); // 等待视频开始播放
        
        // 连接WebSocket
        connectWebSocket();
        
        // 其余代码保持不变...
    } catch (error) {
        console.error('无法访问摄像头：', error);
        document.getElementById('statusMessage').textContent = '无法访问摄像头：' + error.message;
        document.getElementById('statusMessage').classList.add('error');
    }
}

// 停止捕捉
function stopCapture() {
    // 停止动画
    if (animationId) {
        cancelAnimationFrame(animationId);
        animationId = null;
    }
    
    // 停止视频流
    if (mediaStream) {
        mediaStream.getTracks().forEach(track => track.stop());
        video.srcObject = null;
    }
    
    // 关闭WebSocket
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.close();
    }
    
    // 清除画布
    originalCtx.clearRect(0, 0, originalCanvas.width, originalCanvas.height);
    resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
    
    // 更新UI
    document.getElementById('startButton').disabled = false;
    document.getElementById('stopButton').disabled = true;
    document.getElementById('statusMessage').textContent = '捕捉已停止';
    document.getElementById('fpsCounter').textContent = 'FPS: 0';
}

function connectWebSocket() {
    // 动态获取当前页面的主机名和协议
    const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${location.host}/ws`;
    console.log("正在连接到 WebSocket:", wsUrl);
    
    // 删除这行重复代码
    // websocket = new WebSocket(wsUrl);
    websocket = new WebSocket(wsUrl);
    
    websocket.onopen = function() {
        console.log('WebSocket连接已建立');
        document.getElementById('statusMessage').textContent = '已连接到服务器';
        
        // 在连接成功后开始处理视频帧
        requestAnimationFrame(processFrame);
    };
    websocket.onerror = function(error) {
        console.error('WebSocket错误:', error);
        document.getElementById('statusMessage').textContent = '服务器连接错误';
        document.getElementById('statusMessage').classList.add('error');
    };
    
    websocket.onclose = function() {
        console.log('WebSocket连接已关闭');
        if (document.getElementById('startButton').disabled) {
            document.getElementById('statusMessage').textContent = '服务器连接已断开';
            document.getElementById('statusMessage').classList.add('error');
            stopCapture();
        }
    };
    
    websocket.onmessage = function(event) {
        // 处理服务器返回的数据
        const data = JSON.parse(event.data);
        displayResult(data);
        isProcessing = false;
    };
}

// 处理视频帧
function processFrame() {
    animationId = requestAnimationFrame(processFrame);
    
    // 计算FPS
    const now = performance.now();
    frameCount++;
    
    // 每秒更新FPS显示
    if (now - lastFpsUpdate >= 1000) {
        const fps = Math.round((frameCount * 1000) / (now - lastFpsUpdate));
        document.getElementById('fpsCounter').textContent = `FPS: ${fps}`;
        frameCount = 0;
        lastFpsUpdate = now;
    }
    
    // 检查WebSocket连接
    if (!websocket || websocket.readyState !== WebSocket.OPEN) {
        return;
    }
    
    // 如果正在处理前一帧，则跳过
    if (isProcessing) {
        return;
    }
    
    // 绘制原始视频帧
    originalCtx.drawImage(video, 0, 0, originalCanvas.width, originalCanvas.height);
    
    // 获取当前选择的模式
    const modeElements = document.getElementsByName('mode');
    let selectedMode = 'frank';
    for (const element of modeElements) {
        if (element.checked) {
            selectedMode = element.value;
            break;
        }
    }
    
    // 将视频帧转换为base64
    const dataUrl = originalCanvas.toDataURL('image/jpeg', 0.7);
    
    // 发送到服务器
    try {
        websocket.send(JSON.stringify({
            mode: selectedMode,
            image: dataUrl
        }));
        isProcessing = true;
    } catch (error) {
        console.error('发送帧时出错:', error);
        isProcessing = false;
    }
}

// 显示处理结果
function displayResult(data) {
    if (!data.image) {
        return;
    }
    
    // 加载结果图像
    const img = new Image();
    img.onload = function() {
        resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
        resultCtx.drawImage(img, 0, 0, resultCanvas.width, resultCanvas.height);
        
        // 如果有关键点数据，可以在这里绘制额外的信息
        if (data.keypoints && document.getElementById('showSkeleton').checked) {
            drawKeypoints(data.keypoints);
        }
    };
    img.src = data.image;
}

// 绘制关键点
function drawKeypoints(keypoints) {
    // 实现关键点绘制
    const scaleX = resultCanvas.width / 640;
    const scaleY = resultCanvas.height / 480;
    
    resultCtx.fillStyle = 'red';
    resultCtx.strokeStyle = 'yellow';
    resultCtx.lineWidth = 2;
    
    // SMPL骨架连接定义 - 表示哪些关键点应该相互连接
    // 这里使用简化的骨架结构，实际应用可能需要更精确的连接
    const connections = [
        [0, 1], [1, 2], [2, 3], [3, 4],  // 脊柱
        [1, 5], [5, 6], [6, 7],          // 左臂
        [1, 8], [8, 9], [9, 10],         // 右臂
        [0, 11], [11, 12], [12, 13],     // 左腿
        [0, 14], [14, 15], [15, 16]      // 右腿
    ];
    
    // 绘制关键点
    for (let i = 0; i < keypoints.length; i++) {
        const [x, y] = keypoints[i];
        
        resultCtx.beginPath();
        resultCtx.arc(x * scaleX, y * scaleY, 4, 0, 2 * Math.PI);
        resultCtx.fill();
    }
    
    // 绘制骨架连接
    for (const [i, j] of connections) {
        // 确保关键点存在
        if (i < keypoints.length && j < keypoints.length) {
            resultCtx.beginPath();
            resultCtx.moveTo(keypoints[i][0] * scaleX, keypoints[i][1] * scaleY);
            resultCtx.lineTo(keypoints[j][0] * scaleX, keypoints[j][1] * scaleY);
            resultCtx.stroke();
        }
    }
}

// 下载结果图像
function downloadResult() {
    // 创建临时链接
    const link = document.createElement('a');
    link.download = `frankmocap-result-${new Date().toISOString().replace(/[:.]/g, '-')}.png`;
    link.href = resultCanvas.toDataURL('image/png');
    link.click();
}

// 添加下载按钮功能（如果HTML中有下载按钮）
document.addEventListener('DOMContentLoaded', function() {
    const downloadButton = document.getElementById('downloadButton');
    if (downloadButton) {
        downloadButton.addEventListener('click', downloadResult);
    }
});